package com.tanhua.server.service;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.tanhua.autoconfig.template.SmsTemplate;
import com.tanhua.dubbo.api.*;
import com.tanhua.model.domain.*;
import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.PageResult;
import com.tanhua.model.vo.SettingsVO;
import com.tanhua.server.exception.BusinessException;
import com.tanhua.server.interceptor.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Xiao
 * @date 2021/10/23
 */
@Service
@Slf4j
public class SettingsService {
    @DubboReference
    private SettingsApi settingsApi;
    @DubboReference
    private QuestionApi questionApi;
    @DubboReference
    private BlackListApi blackListApi;
    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private RedisTemplate redisTemplate;
    @DubboReference
    private UserApi userApi;

    /**
     * 获取通用设置信息
     * @return
     */
    public SettingsVO getSettingsVO() {
        SettingsVO settingsVO = new SettingsVO();
        Long userId = UserHolder.getUserId();
        settingsVO.setId(userId);
        settingsVO.setPhone(UserHolder.getMobile());

        Question question = questionApi.selectByUserId(userId);
        String strangerQuestion = question == null ? "你喜欢听音乐吗？" : question.getTxt();
        settingsVO.setStrangerQuestion(strangerQuestion);

        Settings settings = settingsApi.selectByUserId(userId);
        if (settings != null) {
            BeanUtils.copyProperties(settings, settingsVO);
        }
        return settingsVO;
    }

    /**
     * 更新陌生人问题
     * @param content
     */
    public void questions(String content) {
        Long userId = UserHolder.getUserId();
        Question question = questionApi.selectByUserId(userId);
        if (question == null) {
            question = new Question();
            question.setUserId(userId);
            question.setTxt(content);
            questionApi.save(question);
        } else {
            question.setTxt(content);
            questionApi.updateById(question);
        }
    }

    /**
     * 通知设置
     * @param likeNotification
     * @param pinglunNotification
     * @param gonggaoNotification
     */
    public void notificationsSetting(
            Boolean likeNotification,
            Boolean pinglunNotification,
            Boolean gonggaoNotification) {
        Long userId = UserHolder.getUserId();
        Settings settings = settingsApi.selectByUserId(userId);
        if (settings == null) {
            settings = new Settings();
            settings.setUserId(userId);
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.save(settings);
        } else {
            settings.setLikeNotification(likeNotification);
            settings.setPinglunNotification(pinglunNotification);
            settings.setGonggaoNotification(gonggaoNotification);
            settingsApi.updateById(settings);
        }
    }

    /**
     * 黑名单-翻页列表
     * @param page
     * @param pagesize
     * @return
     */
    public PageResult blackList(Integer page, Integer pagesize) {
        Long userId = UserHolder.getUserId();
        IPage<BlackList> iPage = blackListApi.page(userId, page, pagesize);
        List<BlackList> blackLists = iPage.getRecords();
        if (blackLists.size() == 0) {
            return null;
        }
        List<Long> blackUserIds = new ArrayList<>();
        for (BlackList blackList : blackLists) {
            blackUserIds.add(blackList.getBlackUserId());
        }
        List<UserInfo> userInfos = userInfoApi.selectByIds(blackUserIds);
        return new PageResult(page, pagesize, Integer.parseInt(String.valueOf(iPage.getTotal())), userInfos);

    }

    /**
     * 移除黑名单
     * @param blackUserId
     */
    public void removeBlacklist(Long blackUserId) {
        blackListApi.removeByUid(UserHolder.getUserId(), blackUserId);
    }

    /**
     * 修改手机号-发送验证码
     */
    public void sendVerificationCode() {
        String mobile = UserHolder.getMobile();
        //        String code = RandomStringUtils.randomNumeric(6);
        String code = "123456";
        log.info("mobile:{}, code:{}", mobile, code);
//        smsTemplate.sendSms(phone, code);
        redisTemplate.opsForValue().set("Verification_Code_" + mobile, code, Duration.ofMinutes(5L));
    }

    /**
     * 修改手机号-校验验证码
     * @param verificationCode
     * @return
     */
    public Boolean checkVerificationCode(String verificationCode) {
        String key = "Verification_Code_" + UserHolder.getMobile();
        String codeInRedis = (String) redisTemplate.opsForValue().get(key);
        if (StringUtils.isEmpty(codeInRedis) || !verificationCode.equals(codeInRedis)) {
            throw new BusinessException(ErrorResult.loginError());
        }
        redisTemplate.delete(key);
        return true;
    }

    /**
     * 修改手机号-保存
     * @param phone
     */
    public void phone(String phone) {
        User user = userApi.isMobileExit(phone);
        if (user != null) {
            throw new BusinessException(ErrorResult.mobileError());
        }
        user = UserHolder.get();
        user.setMobile(phone);
        userApi.updateById(user);
    }
}
